const LOGIN_ERROR = 50001 //登录失败
const LOGIN_EXPIRE = 40001 //登录过期
const toPromise = require("./to-promise")
const regeneratorRuntime = require("../vendor/regenerator-runtime")
const co = require("../vendor/co")
const loginUrl = "city/login/index"
const maxRetry = 3
let retry = 0
// let baseUrl = "https://shop.zhzhsq.com/v1/";//请求根地址
// let baseUrl = "http://front.zhaohu.com/v1/";//请求根地址
// let baseUrl = "http://f.zh.com/";//请求根地址
// let baseUrl = "https://city.zhzhsq.com/"; //请求根地址

let baseUrl = 'http://frontend.c2c.com/'

function doRequest(config) {
    const app = getApp()
    return co(function*() {
        //sid
        let sid = wx.getStorageSync('sid')
        if (!sid) {
            //wx login
            let loginRes = yield app.toPromise(wx.login)
            // console.log(loginRes)
            let loginInfo = yield app.toPromise(wx.request, {
                url: baseUrl + loginUrl,
                header: {
                    'store-id': app.storeId,
                    'Code': loginRes.code
                }
            })
            if (loginInfo.data.status.code == 2000) {
                //login success
                wx.setStorage({
                    key: 'sid',
                    data: loginInfo.data.data.sid
                })
                sid = loginInfo.data.data.sid
                wx.setStorage({
                    key: 'mid',
                    data: loginInfo.data.data.member_id
                })
                wx.setStorage({
                    key: 'store',
                    data: loginInfo.data.data.store_name
                })
            } else {
                wx.hideLoading()
                return Promise.reject({
                    message: '登录失败',
                    code: LOGIN_ERROR
                })
            }
        }
        let cfg = Object.assign({}, config)
        if (!cfg.header) {
            cfg.header = {}
        }
        cfg.header['store-id'] = app.storeId
        cfg.header['sid'] = sid
        let res = yield app.toPromise(wx.request, cfg)
        if (res.data.status.code != 2000) {
            //请求错误
            return Promise.reject(res.data.status)
        }
        return res.data
    })
}

function req(config) {
    let retry = 5
    config = Object.assign({
        showMsg: true
    }, config);
    return doRequest(config).then(res => {
        return Promise.resolve(res)
    }).catch(err => {
        if (err.code == LOGIN_EXPIRE) {
            //登录过期
            retry--
            if (retry > 0) {
                wx.removeStorageSync('sid')
                return doRequest(config)
            }
            return Promise.reject({
                message: '请求失败',
                code: -1
            })
        }
        if (err.code == LOGIN_ERROR) {
            wx.showModal({
                title: '提示',
                content: '登录失败，请删除小程序后重试',
                showCancel: false,
                success: res => {
                    wx.removeStorage({
                        key: 'sid',
                        success: function(res) {},
                    })
                    res.confirm && wx.navigateBack({

                    })
                }
            })
        }

        err.message && config.showMsg && getApp().wxToast.error(err.message)
        return Promise.reject(err)
    })
}
module.exports = {
    get: function(url, config = {}) {
        config.url = (config.baseUrl || baseUrl) + url
        config.method = "GET"
        return req(config)
    },
    post: function(url, config = {}) {
        config.url = (config.baseUrl || baseUrl) + url
        config.method = "POST"
        return req(config)
    },
    getBaseUrl() {
        return baseUrl
    }
}